/* Copyright (c) 2012 Ronan Mac an tSaoir

	 Licensed under the Apache License, Version 2.0 (the "License");
	 you may not use this file except in compliance with the License.
	 You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

	 Unless required by applicable law or agreed to in writing, software
	 distributed under the License is distributed on an "AS IS" BASIS,
	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 See the License for the specific language governing permissions and
	 limitations under the License.
*/

package com.enjoyireland.hiking;

import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.List;

import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.PathOverlay;

import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;

/**
 * Utility class to asynchronously run GPX parsing (time consuming process)
 * 
 * @author Rónan Mac an tSaoir
 *
 */
public class GPXViewer {

	Location _startingPoint = null;
	
	public GPXViewer(InputStream gpxStream, MapView map) {
		parseGPX(gpxStream,map);
	}

	public void parseGPX(InputStream gpxFile, MapView map){
		GPXParser parser = new GPXParser(map);
		parser.execute(gpxFile);
	}
	
	/*  */
	class GPXParser extends AsyncTask<InputStream, Void, List<Location>> {
		private final WeakReference<MapView> mapRef;

	    public GPXParser(MapView map) {
	        mapRef = new WeakReference<MapView>(map);
	    }

	    @Override
	    /* Actual parsing started here, run in the task thread */
	    protected List<Location> doInBackground(InputStream... params) {
	         return MapUtils.getGPXPoints(params[0]);
	    }

	    @Override
	    /* Once the GPX track is parsed, update map view */
	    protected void onPostExecute(List<Location> points) {
	        if (isCancelled()) {
	            points = null;
	        }
	        if (mapRef != null) {
	            MapView map = mapRef.get();
	            if (map != null) {
	            	PathOverlay gpxTrack = new PathOverlay(Color.RED, map.getContext());
	                for (final Location point : points){
	                	gpxTrack.addPoint(new GeoPoint(point.getLatitude(),point.getLongitude()));
	                }
	                _startingPoint = points.get(0);
	        		/* Add GPX overlay for walk */
	        		map.getOverlays().add(gpxTrack);
	            }
	        }
	    }
	}
}